package com.ethink.order.manager;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ethink.framework.common.constant.CommonRespCode;
import com.ethink.framework.common.exception.BusinessException;
import com.ethink.order.api.constant.OrderRespCode;
import com.ethink.order.api.enums.PurchaseOrderDetailStatusEnum;
import com.ethink.order.api.enums.PurchaseOrderStatusEnum;
import com.ethink.order.api.info.PurchaseOrderDetailInfo;
import com.ethink.order.api.info.PurchaseOrderInfo;
import com.ethink.order.api.model.PurchaseDetailModel;
import com.ethink.order.api.model.TransferPurchaseOrderModel;
import com.ethink.order.api.request.PurchaseOrderAddRequest;
import com.ethink.order.api.request.PurchaseOrderUpdateRequest;
import com.ethink.order.api.request.TransferPurchaseOrderRequest;
import com.ethink.order.api.response.PurchaseOrderDetailQueryResponse;
import com.ethink.order.api.response.TransferPurchaseResponse;
import com.ethink.order.common.entity.PurchaseOrder;
import com.ethink.order.common.entity.PurchaseOrderDetail;
import com.ethink.order.common.mapper.PurchaseOrderDetailMapper;
import com.ethink.order.common.mapper.PurchaseOrderMapper;
import com.ethink.order.service.PurchaseOrderDetailService;
import com.ethink.order.service.PurchaseOrderService;
import com.fasterxml.jackson.databind.BeanProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author default
 * @version 1.0.0
 * @ClassName PurchaseManager.java
 * @Description
 * @createTime 2022年11月04日 22:25:00
 */
@Component
@Transactional(rollbackFor = Exception.class)
public class PurchaseManager {

    @Autowired
    private PurchaseOrderDetailMapper purchaseOrderDetailMapper;

    @Autowired
    private PurchaseOrderService purchaseOrderService;

    @Autowired
    private PurchaseOrderDetailService purchaseOrderDetailService;

    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;

    @Autowired
    private OaPayManager oaPayManager;

    public TransferPurchaseResponse transferPurchaseOrder(TransferPurchaseOrderRequest request) {
        TransferPurchaseResponse response = new TransferPurchaseResponse();
        List<PurchaseOrderDetail> purchaseOrderDetails = purchaseOrderDetailMapper.selectList(
                new LambdaQueryWrapper<PurchaseOrderDetail>()
                        .eq(PurchaseOrderDetail::getDetailOrderStatus, PurchaseOrderDetailStatusEnum.S2.getIntValue())
                        .eq(PurchaseOrderDetail::getCreateUserCode,request.getCreateUserCode())
                        .in(PurchaseOrderDetail::getId, request.getIds())
        );
        //校验规则
        if (purchaseOrderDetails.size() < request.getIds().size()) {
            throw new BusinessException(OrderRespCode.THE_BID_WAS_NOT_AWARDED);
        }
        Map<String, List<PurchaseOrderDetail>> group = purchaseOrderDetails.stream().collect(Collectors.groupingBy(s -> s.getSaleDemandOrderNo() + "-" + s.getSupplierCode()));
        if (group.size() > 1) {
            throw new BusinessException(OrderRespCode.ONLY_ONE);
        }
        List<TransferPurchaseOrderModel> item = purchaseOrderDetailMapper.selectTransferBase(request);
        TransferPurchaseOrderModel transferPurchaseOrderModel = item.get(0);
        BigDecimal total = item.stream().reduce(BigDecimal.ZERO, (x, y) -> x.add(y.getPurchasePrice().multiply(new BigDecimal(y.getLockOrderQty()))), BigDecimal::add);
        response.setItem(item);
        response.setSaleChannel(transferPurchaseOrderModel.getSaleChannel());
        response.setSaleSubChannel(transferPurchaseOrderModel.getSaleSubChannel());
        response.setSupplierCode(transferPurchaseOrderModel.getSupplierCode());
        response.setSupplierName(transferPurchaseOrderModel.getSupplierName());
        response.setOrderNo(transferPurchaseOrderModel.getOrderNo());
        response.setOrderPrice(total);
        return response;
    }

    public void add(PurchaseOrderAddRequest request) {
        List<PurchaseOrderDetail> purchaseOrderDetails = purchaseOrderDetailMapper.selectBatchIds(request.getIds());
        //计算订单金额
        BigDecimal orderPirce = getOrderPrice(purchaseOrderDetails);
        PurchaseOrderDetail purchaseOrderDetail = purchaseOrderDetails.get(0);
        request.setSaleDemandOrderNo(purchaseOrderDetail.getSaleDemandOrderNo());
        request.setCurrencyCode(purchaseOrderDetail.getCurrencyCode());
        request.setCurrencyName(purchaseOrderDetail.getCurrencyName());
        request.setOrderPrice(orderPirce);
        PurchaseOrder purchaseOrder = purchaseOrderService.add(request);
        purchaseOrderDetailService.bulkBindOrderNo(request.getIds(), purchaseOrder.getOrderNo());
        if (PurchaseOrderStatusEnum.S2.getIntValue().equals(request.getOrderStatus())) {
            PurchaseOrderDetailQueryResponse response = purchaseOrderService.queryPurchaseOrderDetail(purchaseOrder.getId());
            oaPayManager.insert(response.getMain(),response.getItem() );
        }
    }

    private BigDecimal getOrderPrice(List<PurchaseOrderDetail> purchaseOrderDetails) {
        return purchaseOrderDetails.stream().reduce(BigDecimal.ZERO, (x, y) -> x.add(y.getFinalPurchasePrice()
                .multiply(new BigDecimal(y.getLockOrderQty()))), BigDecimal::add);
    }

    @Transactional(rollbackFor = Exception.class)
    public Integer purchaseOrderVoid(Long id) {
        PurchaseOrder purchaseOrder = purchaseOrderMapper.selectById(id);
        if (PurchaseOrderStatusEnum.S2.getIntValue() < purchaseOrder.getOrderStatus()) {
            throw new BusinessException(CommonRespCode.SYSTEM_ERR.getCode(), "仅支持草稿,待付款状态操作");
        }
        purchaseOrderDetailMapper.update(null, new LambdaUpdateWrapper<PurchaseOrderDetail>()
                .eq(PurchaseOrderDetail::getOrderNo, purchaseOrder.getOrderNo())
                .set(PurchaseOrderDetail::getOrderNo, null));
        return purchaseOrderMapper.delById(id);
    }

    public Integer purchaseOrderUpdate(PurchaseOrderUpdateRequest updateRequest) {
        PurchaseOrder purchaseOrder = purchaseOrderMapper.selectById(updateRequest.getId());
        List<PurchaseOrderDetail> purchaseOrderDetails = purchaseOrderDetailMapper.selectBatchIds(updateRequest.getIds());
        BigDecimal orderPrice = getOrderPrice(purchaseOrderDetails);
        updateRequest.setOrderPrice(orderPrice);
        purchaseOrderMapper.purchaseOrderUpdate(updateRequest);
        purchaseOrderDetailMapper.update(null, new LambdaUpdateWrapper<PurchaseOrderDetail>()
                .eq(PurchaseOrderDetail::getOrderNo, purchaseOrder.getOrderNo())
                .set(PurchaseOrderDetail::getOrderNo, null));
        purchaseOrderDetailService.bulkBindOrderNo(updateRequest.getIds(), purchaseOrder.getOrderNo());
        if (PurchaseOrderStatusEnum.S2.getIntValue().equals(updateRequest.getOrderStatus())) {
            PurchaseOrderDetailQueryResponse response = purchaseOrderService.queryPurchaseOrderDetail(purchaseOrder.getId());
            oaPayManager.insert(response.getMain(), response.getItem());
        }
        return 1;
    }
}
